import { PrismaClient } from '@prisma/client'
import { logger } from '../services/logger'
import { validateWorkflow, validateTemplate } from '../utils/workflow'

const prisma = new PrismaClient()

async function checkWorkflows() {
    try {
        const workflows = await prisma.workflow.findMany()
        let hasErrors = false

        for (const workflow of workflows) {
            logger.info(`Checking workflow: ${workflow.id}`)

            // 检查工作流配置
            try {
                const workflowConfig = JSON.parse(workflow.workflow)
                if (!validateWorkflow(workflowConfig)) {
                    logger.error(`Invalid workflow configuration: ${workflow.id}`)
                    hasErrors = true
                }
            } catch (error) {
                logger.error(`Failed to parse workflow: ${workflow.id}`, error)
                hasErrors = true
            }

            // 检查模板配置
            try {
                const template = JSON.parse(workflow.template)
                if (!validateTemplate(template)) {
                    logger.error(`Invalid template configuration: ${workflow.id}`)
                    hasErrors = true
                }
            } catch (error) {
                logger.error(`Failed to parse template: ${workflow.id}`, error)
                hasErrors = true
            }

            // 检查关联数据
            const executions = await prisma.execution.findMany({
                where: { workflowId: workflow.id }
            })

            for (const execution of executions) {
                try {
                    JSON.parse(execution.params)
                } catch (error) {
                    logger.error(`Invalid execution params: ${execution.id}`, error)
                    hasErrors = true
                }
            }
        }

        if (!hasErrors) {
            logger.info('All workflows checked successfully')
        }

        return !hasErrors
    } catch (error) {
        logger.error('Failed to check workflows:', error)
        throw error
    }
}

// 执行检查
if (require.main === module) {
    checkWorkflows()
        .then(success => process.exit(success ? 0 : 1))
        .catch(error => {
            console.error(error)
            process.exit(1)
        })
}

export { checkWorkflows }